<route lang="json5">
{
  layout: 'default',
  style: {
    navigationBarTitleText: '标准检索',
  },
}
</route>

<script lang="ts" setup>
import FgFooter from '@/components/fg-footer/fg-footer.vue'

defineOptions({
  name: 'AppSearch',
})

// 获取屏幕边界到安全区域距离
const { safeAreaInsets } = uni.getSystemInfoSync()

// 分类数据
const categories = ref<Array<{ category: string, num: number }>>([])
const selectedCategory = ref('all')

// 标准列表数据
const standardList = ref<
  Array<{
    id: number
    category: string
    communityName: string
    standardNumber: string
    standardName: string
    publicationDate: string
    status: string
    draftingUnit: string
    technicalContent: string
    publishment: boolean
    standardTextName: string
    standardTextAddress: string
  }>
>([])

// 搜索关键词
const searchKeyword = ref('')

// 分页相关
const currentPage = ref(1)
const pageSize = 10
const hasMore = ref(true)
const isLoading = ref(false)

// 加载分类统计
async function loadCategories() {
  try {
    const response = await uni.request({
      url: '/standard/statistics',
      method: 'GET',
    })

    if ((response.data as any)?.success) {
      categories.value = (response.data as any).data || []
      // 添加"全部"选项
      categories.value.unshift({ category: '全部', num: 0 })
      selectedCategory.value = 'all'
    }
  }
  catch (error) {
    console.error('加载分类失败:', error)
  }
}

// 加载标准列表
async function loadStandards() {
  if (isLoading.value || !hasMore.value)
    return

  isLoading.value = true
  try {
    const params: Record<string, any> = {
      'condition.page': currentPage.value,
      'condition.size': pageSize,
    }

    // 添加分类筛选
    if (selectedCategory.value && selectedCategory.value !== 'all') {
      params['condition.category'] = selectedCategory.value
    }

    // 添加关键词搜索
    if (searchKeyword.value.trim()) {
      params['condition.keyword'] = searchKeyword.value.trim()
    }

    console.log('加载标准参数:', params)
    const response = await uni.request({
      url: '/standard/h5',
      method: 'GET',
      data: params,
    })

    if ((response.data as any)?.success) {
      const newStandards = (response.data as any).data?.data || []

      if (currentPage.value === 1) {
        standardList.value = newStandards
      }
      else {
        standardList.value.push(...newStandards)
      }

      hasMore.value = newStandards.length === pageSize
      if (hasMore.value) {
        currentPage.value++
      }
    }
  }
  catch (error) {
    console.error('加载标准失败:', error)
  }
  finally {
    isLoading.value = false
  }
}

// 防抖定时器
let debounceTimer: number | null = null

// 分类切换
function handleCategoryChange(category: string) {
  console.log('切换到分类:', category)

  // 清除之前的定时器
  if (debounceTimer) {
    clearTimeout(debounceTimer)
  }

  // 防抖处理
  debounceTimer = setTimeout(() => {
    if (selectedCategory.value !== category) {
      selectedCategory.value = category
      currentPage.value = 1
      hasMore.value = true
      standardList.value = [] // 清空当前列表
      loadStandards()
    }
  }, 100) // 100ms 防抖
}

// 搜索处理
function handleSearch() {
  currentPage.value = 1
  hasMore.value = true
  standardList.value = []

  // 防抖处理
  setTimeout(() => {
    loadStandards()
  }, 300)
}

// 格式化日期
function formatDate(dateStr: string) {
  if (!dateStr)
    return ''
  return dateStr.split(' ')[0] // 只显示日期部分
}

// 获取分类标题（优化显示）
function getCategoryTitle(category: any) {
  const name = category.category || ''
  const count = category.num || 0

  // 进一步缩短文字，只显示前4个字符
  let displayName = name
  if (name.length > 4) {
    displayName = `${name.substring(0, 4)}...`
  }

  // 简化显示：只显示分类名，数量用小字显示
  return displayName
}

// 页面初始化
onMounted(() => {
  loadCategories()
  loadStandards()
})

// 触底加载更多
onReachBottom(() => {
  loadStandards()
})
</script>

<template>
  <view
    class="min-h-screen"
    :style="{
      marginTop: `${safeAreaInsets?.top}px`,
      background: 'linear-gradient(to bottom, #E9F0FF, #F2F5F9)',
    }"
  >
    <!-- 搜索区域 -->
    <view
      class="sticky top-0 z-10 px-4 py-3"
      :style="{ background: 'linear-gradient(to bottom, #E9F0FF, #F2F5F9)' }"
    >
      <view class="flex items-center rounded-lg bg-white px-4 py-2 shadow-sm">
        <text class="i-carbon-search mr-3 text-xl text-gray-400" />
        <input
          v-model="searchKeyword"
          placeholder="请输入标准名称或编号"
          class="flex-1 text-gray-700"
          @input="handleSearch"
        >
      </view>
    </view>

    <!-- 分类选择器 -->
    <view
      class="sticky top-16 z-10 px-4 py-2"
      :style="{ background: 'linear-gradient(to bottom, #E9F0FF, #F2F5F9)' }"
    >
      <scroll-view scroll-x class="whitespace-nowrap">
        <view class="flex space-x-2">
          <view
            v-for="category in categories"
            :key="category.category"
            class="inline-flex items-center whitespace-nowrap rounded-full px-3 py-1.5 text-xs font-medium"
            :class="
              selectedCategory === (category.category === '全部' ? 'all' : category.category)
                ? 'bg-blue-500 text-white'
                : 'bg-white text-gray-600 border border-gray-200'
            "
            @click="handleCategoryChange(category.category === '全部' ? 'all' : category.category)"
          >
            {{ getCategoryTitle(category) }}
            <text v-if="category.num > 0" class="ml-1 text-xs opacity-70">
              {{ category.num }}
            </text>
          </view>
        </view>
      </scroll-view>
    </view>

    <!-- 标准列表 -->
    <view class="px-4 pb-20">
      <view v-if="standardList.length === 0 && !isLoading" class="py-20 text-center">
        <text class="i-carbon-document text-6xl text-gray-300" />
        <view class="mt-4 text-gray-500">
          暂无标准数据
        </view>
      </view>

      <view v-else class="space-y-4">
        <view
          v-for="standard in standardList"
          :key="standard.id"
          class="rounded-xl bg-white p-4 shadow-sm"
        >
          <!-- 标准标题 -->
          <view class="mb-3">
            <view class="mb-1 text-lg text-gray-800 font-semibold">
              {{ standard.standardName }}
            </view>
            <view class="text-sm text-gray-500">
              {{ standard.standardNumber }}
            </view>
          </view>

          <!-- 标准信息 -->
          <view class="mb-3 space-y-2">
            <view class="flex items-center text-sm">
              <text class="w-20 text-gray-500">
                分类:
              </text>
              <text class="text-gray-700">
                {{ standard.category }}
              </text>
            </view>
            <view class="flex items-center text-sm">
              <text class="w-20 text-gray-500">
                状态:
              </text>
              <text class="text-gray-700">
                {{ standard.status }}
              </text>
            </view>
            <view class="flex items-center text-sm">
              <text class="w-20 text-gray-500">
                发布日期:
              </text>
              <text class="text-gray-700">
                {{ formatDate(standard.publicationDate) }}
              </text>
            </view>
            <view class="flex items-center text-sm">
              <text class="w-20 text-gray-500">
                起草单位:
              </text>
              <text class="text-gray-700">
                {{ standard.draftingUnit }}
              </text>
            </view>
            <view class="flex items-center text-sm">
              <text class="w-20 text-gray-500">
                团体名称:
              </text>
              <text class="text-gray-700">
                {{ standard.communityName }}
              </text>
            </view>
          </view>

          <!-- 技术内容 -->
          <view v-if="standard.technicalContent" class="mb-3">
            <view class="mb-1 text-sm text-gray-500">
              主要技术内容:
            </view>
            <view class="line-clamp-3 text-sm text-gray-700">
              {{ standard.technicalContent }}
            </view>
          </view>

          <!-- 标准文本链接 -->
          <view v-if="standard.standardTextAddress" class="flex items-center justify-between">
            <view class="flex items-center text-sm text-blue-500">
              <text class="i-carbon-document mr-1" />
              <text>{{ standard.standardTextName || '查看标准文本' }}</text>
            </view>
            <view class="text-xs text-gray-400">
              {{ standard.publishment ? '公开' : '非公开' }}
            </view>
          </view>
        </view>
      </view>

      <!-- 加载状态 -->
      <view v-if="isLoading" class="py-8 text-center">
        <text class="i-carbon-loading animate-spin text-2xl text-gray-400" />
        <view class="mt-2 text-sm text-gray-500">
          加载中...
        </view>
      </view>

      <!-- 没有更多数据 -->
      <view v-if="!hasMore && standardList.length > 0" class="py-8 text-center">
        <view class="text-sm text-gray-400">
          没有更多数据了
        </view>
      </view>
    </view>

    <!-- 底部信息 -->
    <FgFooter />
  </view>
</template>

<style scoped>
.line-clamp-3 {
  display: -webkit-box;
  -webkit-line-clamp: 3;
  -webkit-box-orient: vertical;
  overflow: hidden;
}
</style>
